<template>
	<view class="container">
		<view class="header-backgroud-box">
			<text class="header-backgroud-box-title">yzLinker</text>
			<text class="header-backgroud-box-content">基于ESP8266的通用控制器</text>
		</view>
		<uni-card title="基础信息" class="">
			<view class="device-name-line">
				<text>名称：</text>
				<input
					:class="modify_device_name?'device-name-input':'device-name-input-normal'"
					:value="device_name" @input="onDeviceNameInput" @longpress="modifyDeviceName"
					:disabled="modify_device_name?false:true" confirm-type="send"
					@confirm="onDeviceNameModifyComplate" />
			</view>
			<view class="normal-info-line">
				<text>类型：{{type_str}}</text>
			</view>
			<view class="normal-info-line">
				<text>设备ID：{{device_id}}</text>
			</view>
			<view class="normal-info-line">
				<text>设备状态：正常运行</text>
			</view>
		</uni-card>
		<uni-card title="设备控制">
			<view v-for="(item,index) in device_switch_list" :key="item.index">
				<my-switchs :type="parseInt(device_switch_type)" :title="item.title" :select="item.status" @status="item.callback(index,$event)"></my-switchs>
			</view>
		</uni-card>
		<uni-card title="定时器列表">
			<uni-list v-for="(item,index) in device_tiemr_list" :key="item.timeout">
				<uni-list-item :title="item.timeout" :note="timerStatusShow(index)"
					:rightText="item.type==0?'周期性触发':'一次性触发'" :showArrow="true" :clickable="true"
					@click="addModifyTimer(index)"
					></uni-list-item>
			</uni-list>
			<view class="add-device-btn">
				<button :type="'primary'" @click="addModifyTimer(null)">添加定时器</button>
			</view>
		</uni-card>
	</view>
</template>

<script>
	import {
		commonData
	} from '@/utils/common.js'
	let tools = require('@/utils/tools');
	export default {
		data() {
			return {
				//基础信息
				device_name:'esp8266 device',
				modify_device_name:false,
				device_id:'',
				type_str:'未知',
				
				//设备控制
				device_switch_num:1,
				device_switch_type:2,
				device_switch_list:[],
				
				//定时器列表
				device_tiemr_list:[]
			}
		},
		onLoad() {
			this.hide = false; //关闭Mqtt操作由于Hide显示产生，此时不边切换界面
			
			//获取前一个页面传递过来的被选择的设备ID。
			this.device_id = commonData.curDevice?commonData.curDevice:"8f5e2300";
			
			//被选择的对像
			this.common_device = this.getCurDevice(this.device_id);
			if(this.common_device == undefined){
				console.log('无效的设备ID')
				this.goBack();
			}
			
			//识别设备类型
			let ret = tools.analyDeviceType(this.common_device.type);
			if(ret.sw_num==-1){
				console.log('设备类型：'+this.common_device.type+' 不支持！')
				this.goBack();
				return '不支持';
			}else if(ret.sw_num==0 && ret.sw_type == 0){
				console.log('设备类型：'+this.common_device.type+' 未知！')
				this.goBack();
				return '未知';
			}else{
				this.device_switch_num = ret.sw_num;
				this.device_switch_type = ret.sw_type;
			}
			
			//初始化设备控制面板中的开关列表
			this.initDeviceSwitchs();			
			
			// Mqtt连接与退出回调函数在此处注册
			commonData.mqtt.onConnect = ()=>{
				console.log('connect on device page.');
				this.initMqttMsg();
			}
			commonData.mqtt.onConnectFaild = (error)=>{
				console.log('connect mqtt server faild.',error)
				uni.showToast({
					title:'连接失败！',
					icon:'error'
				})
			}
			commonData.mqtt.onExit = ()=>{
				if(!this.hide){
					uni.redirectTo({
						url:'/pages/login/login',
						success() {
							console.log('back login page success.')
						},
						fail(e) {
							console.log('faild to back login page.'+JSON.stringify(e))
						}
					})
				}
				this.hide = false;
			}
			
			if(commonData.mqtt.isConnected()){
				console.log('have connected.')
				this.initMqttMsg();
			}else{
				commonData.mqtt.login();
			}
			
			this.updateDeviceList();
		},
		onShow() {
			console.log('on show.')
			if(!commonData.mqtt.isConnected()){
				commonData.mqtt.login();
				//this.updateDeviceList();
			}else{
				console.log('connected.')
			}
			
			//这里加入设置定时器页面返回检测
			console.log('timer set:'+JSON.stringify(commonData.timerSet))
			//定时器列表界面返回信息检测
			this.timersCommand();
			this.updateDeviceList();
		},
		onHide() {
			console.log('on hide.')
			if(commonData.mqtt.isConnected()){
				commonData.mqtt.close();
				this.hide = true;
			}
		},
		methods: {
			/******************
			  初始化界面相关功能代码
			******************/
			//获取当前选中设备在commData中的实际内容
			getCurDevice(device_id){
				//获取被选择的设备在commonData的deviceList中的实际内容
				let device_index = tools.findIdInDeviceList(device_id,commonData)
				if(device_index == -1){
					console.log('device id:'+device_id+"not found in commonData.")
					return undefined;
				}
				return commonData.deviceList[device_index];
			},
			//初始化设备控制面板中的开关列表
			initDeviceSwitchs(){
				//初始化设备状态
				this.device_switch_list = []
				for (let i = 0; i < this.device_switch_num; i++) {
					let item = {
						'index': i,
						'title': '开关' + (i + 1) + '状态：',
						'status': 0,
						'callback': this.onSwitchChange
					}
					this.device_switch_list.push(item)
				}
				//个性化定制
				if (this.device_switch_num == 1) {
					this.device_switch_list[0].title = '开关状态：'
				} else if (this.device_switch_num == 2) {
					this.device_switch_list[0].title = '左侧状态：';
					this.device_switch_list[1].title = '右侧状态：';
				}
			},
			onSwitchChange(index, value) {
				console.log('index:' + index + ";value:" + value)
				//this.publishWithID(this.device_info_id, "switch/change", JSON.stringify({index:index,value:value}))
			},
			/******************
			  UI相关功能代码
			******************/
			
			//长按设备名称时，允许修改设备名称
			modifyDeviceName() {
				this.modify_device_name = true;
			},
			//当设备名称输入框发生变化时的回调
			onDeviceNameInput(e) {
				console.log(e.detail.value)
				let old = this.device_name;
				//只允许输入字母、数字、下划线及空格组成的英文名称标识
				// （中文名称标识Esp8266设备Mqtt会出错）
				if (/^[a-zA-Z0-9_\s]+$/g.test(e.detail.value)) {
					console.log('ok:' + e.detail.value)
					this.device_name = e.detail.value
				} else {
					if (e.detail.value === '') {
						console.log('empty')
						this.$nextTick(() => {
							this.device_name = this.device_name;
						})
					}
					this.device_name = '';
					this.$nextTick(() => {
						//用于在输入不合规时，恢复原来的数据
						this.device_name = old;
					})
				}
			},
			onDeviceNameModifyComplate(e) {
				console.log(e.detail.value)
				//加入修改设备名称功能
				//this.publishWithID(this.device_info_id, "newtitle", JSON.stringify({name:e.detail.value}))
				this.modify_device_name = false;
			},
			//获取开关类型描述字符串
			getSwitchTypeStr(type){
				return tools.switchTypeStr(type);
			},
			//定时器列表项开关状态描述字符串
			timerStatusShow(index) {
				let show_str = '';
				//let item = this.device_tiemr_list[index];
				let item = commonData.timerList[index];
				if (this.device_switch_num == 1) {
					show_str = this.getTimerStatusStr(item.status[0].sw_status) // == 0 ? '关' : '开';
					return '开关状态：' + show_str;
				} else if (this.device_switch_num == 2) {
					
					for (let i in item.status) {
						if (i >= this.device_switch_num) {
							break;
						}
						let status_item = item.status[i];
						if (status_item.id == 0) {
							show_str += '左侧：'
						} else {
							show_str += '右侧：'
						}
						let temp = this.getTimerStatusStr(status_item.sw_status) //status_item.sw_status == 0 ? '关' : '开';
						show_str = show_str + temp + ';'
					}
					return show_str;
				} else {
					let temp_str = '';
					for (let i in item.status) {
						let status_item = item.status[i];
						let temp = this.getTimerStatusStr(status_item.sw_status); //status_item.sw_status == 0 ? '关' : '开';
						let t = parseInt(status_item.id) + 1;
						console.log('t:' + t)
						show_str = show_str + '开关' + t + ':' + temp + ';'
					}
					return show_str;
				}
				return show_str
			},
			getTimerStatusStr(status){
				if(this.device_switch_type == 2){
					return status == 0 ? '关' : '开';
				}else if(this.device_switch_type == 3){
					if(status == 0){
						return '关';
					}else if(status == 1){
						return '中';
					}else{
						return '高';
					}
				}else if(this.device_switch_type == 4){
					if(status == 0){
						return '关';
					}else if(status == 1){
						return '低';
					}else if(status == 2){
						return '中';
					}else{
						return '高';
					}
				}
			},
			//添加或修改定时器按钮回调函数
			addModifyTimer(index) {
				console.log('add or modify timer:' + index);
				//this.show_timer_add_modify_panel = true;
				//此处加入设备开关类型，以便在添加修改定时器页面获取所支持的开关个数
				commonData.curDeviceType = this.device_switch_type;
				commonData.curDeviveNum = this.device_switch_num;
				
				if (index == null) {
					//此时为添加定时器			
					console.log('init timer add timer')
					uni.navigateTo({
						url:"/pages/timers/timers"
					})
				} else {
					console.log('modify timer index:' + index)
					uni.navigateTo({
						url:"/pages/timers/timers?index="+index
					})
				}
			
			},
			
			/*----------------------------
			Mqtt连接成功后，对本页面需要的主题进行订阅，通过指定回调函数的方式一次性评阅
			----------------------------*/
			//初始化每个设备的Mqtt环境，对需要的主题进行订阅
			initMqttMsg(){
				this.initDeviceWithId(this.device_id);
			},
			initDeviceWithId(deviceId){
				//在这里可以加入当前设备需要订阅的主题
				commonData.mqtt.addTopic(deviceId,'info',this.onInfoCallBack)
			},
			onInfoCallBack(id,topic,payload){
				console.log('on line device.')
				console.log('device id is:'+id);
			},
			
			//commonData数据与当前界面交互
			updateDeviceList(){
				console.log(JSON.stringify(this.common_device))
				//基础信息交互
				this.device_name = this.common_device.name;
				this.type_str = this.getSwitchTypeStr(this.common_device.type);
				this.device_tiemr_list = []
				for(let i in commonData.timerList){
					let timer_item = commonData.timerList[i];
					this.device_tiemr_list.push(timer_item)
				}
			},
			//处理timers界面返回的命令
			timersCommand(){
				if(commonData.timerSet == null){
					//没有命令
					return
				}
				if(commonData.timerSet.cmd == 'add'){
					console.log('command add.')
					let add_timer_item = {
						'timeout':commonData.timerSet.timer_item.timeout,
						'type':commonData.timerSet.timer_item.type,
						'status':commonData.timerSet.timer_item.status,
					}
					commonData.timerList.push(add_timer_item)
				}
				commonData.timerSet = null;
			},
			
			/*******************
			*  运行过程出错，异常处理
			*******************/
			goBack(){
				console.log('run error,go back.')
			}
		}
	}
</script>

<style lang="scss">
.container {
		font-size: 28rpx;
		line-height: 48rpx;

		.header-backgroud-box{
			height: 300rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			background-color: white;
			//background-image: url('data:');
			background-size: 60%;
			background-repeat: no-repeat;
			background-position: 90% 0%;
			//border: solid 1rpx cyan;
			.header-backgroud-box-title{
				display: flex;
				margin-left: 50rpx;
				font-size: 2em;
				color: yellowgreen;
				line-height: 100rpx;
			}
			.header-backgroud-box-content{
				display: flex;
				margin-left: 50rpx;
				font-size: 32rpx;
				line-height: 50rpx;
				color: #77eeff;
			}
		}
		
		.device-name-line{
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 10rpx 10rpx;
		
			.device-name-input {
				border: solid 1px blue;
				padding: 5rpx;
				flex-grow: 1;
			}
			
			.device-name-input-normal {
				padding: 5rpx;
				flex-grow: 1;
			}
		
		}
		
		.normal-info-line{
			padding: 5rpx 10rpx;
		}
	}
</style>
